<template>
  <div class="app-container">
    <div v-show="!open">

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="标题" prop="materialTitle">
          <el-input v-model="queryParams.materialTitle" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['system:material:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['system:material:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['system:material:remove']">删除</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['system:material:export']">导出</el-button>
        </el-col> -->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="标题" align="center" prop="materialTitle" />
        <el-table-column label="简介" align="center" prop="materialDigest" />
        <!-- <el-table-column label="作者" align="center" prop="materialAuthor" /> -->
        <el-table-column label="标签id" align="center" prop="labelId" />
        <el-table-column label="封面" align="center" prop="coverUrl" >
          <template slot-scope="scope">
            <div style="width: 125px;padding: 10px;">
            <img style="width: 100%;" :src="scope.row.coverUrl" alt="">
          </div>
          </template>
        </el-table-column>
        <el-table-column label="视频" align="center" prop="audiovisualUrl" >
          <template slot-scope="scope">
            <el-tag type="primary" style="cursor: pointer;" @click="kanshi(scope.row)">查看视频</el-tag>
          <!-- <div  style="width: 135px;" > 
            <video poster="" controls="true" width="auto" height="auto"><source :src="scope.row.audiovisualUrl" type="video/mp4"/></video>
            </div> -->
          </template>
        </el-table-column>
        <!-- <el-table-column label="是否发布到微信：true：同步，false：不同步" align="center" prop="reportWechat" /> -->
        <!-- <el-table-column label="微信返回的素材URL" align="center" prop="wechatUrl" /> -->
        <!-- <el-table-column label="微信返回的永久素材id" align="center" prop="wechatMediaId" /> -->
        <!-- <el-table-column label="操作人ID" align="center" prop="userId" /> -->
        <!-- <el-table-column label="是否删除：true：已删除，false：未删除" align="center" prop="isDelete" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:material:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:material:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body> -->
    <div v-show="open" style="width: 60%;margin: 20px auto;">
      <h2 style="text-align: center;line-height: 70px;border-bottom: 1px solid #ccc;">{{ title }}</h2>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
      
         <el-form-item label="标题" prop="materialTitle">
              <el-input style="width: 250px;" v-model="form.materialTitle" placeholder="请输入标题" />
            </el-form-item>
        <el-form-item label="标签" prop="labelId">
            <el-select style="width: 250px;"
             v-model="form.labelId" placeholder="请选择标签" @change="choosebiao">
              <el-option v-for="item in labellist" :key="item.labelId" :label="item.labelName"
                :value="item.labelId"></el-option>
            </el-select>
            </el-form-item>
     
            <el-form-item label="视频上传"  prop="videoUrl" v-if="form.materialId == null">
              <el-upload class="upload-demo"  :headers="headers" :action="url" :on-success="handlePreview"
                :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1" :data="obj" :on-exceed="handleExceed" 
                :file-list="file" accept=".mp4">
                <el-button size="small" type="primary">点击上传</el-button>

              </el-upload>
            </el-form-item>
            
       <el-form-item label="封面" prop="coverUrl">
              <el-button type="primary" @click="choseimg()">选择封面</el-button>
              <div class="imga" v-if="form.coverUrl" >
                <img :src="form.coverUrl" alt="">
              </div>
            </el-form-item>
       
            <el-form-item label="简介" prop="materialDigest">
              <el-input type="textarea" placeholder="请输入简介" v-model="form.materialDigest" maxlength="100" show-word-limit
                style="width: 500px;" rows="5">
              </el-input>
            </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>

    </div>
    <!-- </el-dialog> -->
    <el-dialog title="选择图片" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <div>
        <div style="width: 50%;margin: 20px auto;">

          <el-steps :active="active" finish-status="success">
            <el-step title="选择图片"></el-step>
            <el-step title="编辑图片"></el-step>
          </el-steps>
        </div>




        <div class="tuuuuuuuu" v-if="active == 1">
          <el-upload class="upload-demo" :action="urll" :on-success="handlePrevieww"
            :on-remove="handleRemovee" :before-remove="beforeRemovee" :on-exceed="handleExceedd"
            :show-file-list="false" :file-list="filetu"
            :headers="headers" 
            accept=".jpg,.png,.webp,.jpep"
            >

            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div class="imglist">
            <div class="imgitem" v-for="(item,index) in imgList" :key="index" 
            @click="chosetu(item)"
            :class="{ activee: activee == item.imgUrl}"> 
             <img :src="item.imgUrl" alt="">
             <p>{{ item.imgName }}</p>
            </div>
          </div>
          <div style="text-align: center;margin-top: 30px;">

            <pagination v-show="totall > 0" :total="totall" 
                  :page-sizes="[14, 20, 30, 40]"
              :page.sync="queryParamss.pageNum" :limit.sync="queryParamss.pageSize"
        @pagination="getListt" />
            <el-button type="primary" @click="choseconfim()" style="margin-top: 20px;">下一步</el-button>

          </div>
        </div>
        <div v-if="active == 2">
          <el-row>
            <el-col :xs="24" :md="12" :style="{ height: '500px' }">
              <vue-cropper ref="cropper" :img="options.img" :info="true" :autoCrop="options.autoCrop"
                :autoCropWidth="options.autoCropWidth" :autoCropHeight="options.autoCropHeight"
                :fixedBox="options.fixedBox" :outputType="options.outputType" @realTime="realTime" v-if="visible" />
            </el-col>
            <el-col :xs="24" :md="12" :style="{ height: '500px' }">
              <div class="avatar-upload-previeww">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </el-col>
          </el-row>
          <div style="text-align: center;margin-top: 50px;">
            <el-button @click="shangyibu()">上一步</el-button>
            <el-button type="primary" @click="uploadImg">确 定</el-button>
          </div>

        </div>

      </div>

    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial,biaoqian ,delvideo,fengmian} from "@/api/system/material";
import { listImg, getImg, delImg, addImg, updateImg } from "@/api/system/img";

import { getToken } from "@/utils/auth";
import { VueCropper } from "vue-cropper";

export default {
  components: { VueCropper },

  name: "Material",
  data() {
    return {
      showaaa: false,
      headers: { Authorization: "Bearer " + getToken() },
      active: 1,
      url: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      obj: {
        oldUrl:" "
      },
      // 【请填写功能名称】表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      visible: true,

      // 是否显示弹出层
      open: false,
      queryParamss: {
        pageNum: 1,
        pageSize: 14,
        imgUrl: null,
        imgType: null,
        reportWechat: null,
        wechatUrl: null,
        wechatMediaId: null,
        userId: null,
        isDelete: null,
      },
      totall:0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialTitle: null,
        materialDigest: null,
        materialAuthor: null,
        labelId: null,
        coverUrl: null,
        videoUrl: null,
        reportWechat: null,
        wechatUrl: null,
        wechatMediaId: null,
        userId: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialTitle: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        labelId: [
          { required: true, message: "标签不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频不能为空" }
        ],
        coverUrl: [
          { required: true, message: "封面不能为空" }
        ],
      },
      file: [],
      filetu:[],
      dialogVisible: false,
      options: {
        img: "", //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 320, // 默认生成截图框宽度
        autoCropHeight: 180, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputType: "png" // 默认生成截图为PNG格式
      },
      previews: {},
      imgList:"",
      labellist:"",
      urll:"",
      activee:"",
      oldUrl:" ",
      type:""
   

    };
  },
  created() {

    this.type=this.$route.query.type
    if(this.type=="1"){
      this.file=[]
      this.reset();
      this.open = true;
      this.title = "添加视频信息";
    }
    this.getbiaoqian()
    this.url = process.env.VUE_APP_BASE_API + "/system/sourceMaterial/sourceMaterialUpload"
    this.urll = process.env.VUE_APP_BASE_API + "/system/sourceMaterialImg/sourceMaterialImgUpload"
    this.getList();
  },
  methods: {
    kanshi(url){
      console.log(url)
  window.open(url.videoUrl)
    },
     // 上传裁剪图片
     uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData();
        formData.append("oldUrl", this.oldUrl);
        formData.append("file", data);
        fengmian(formData).then(response => {
      console.log(response,'123')
      this.oldUrl=response.url
      this.form.coverUrl=this.oldUrl
          this.visible = false;
          this.dialogVisible=false
        });
      });
    },
    chosetu(item){
this.activee=item.imgUrl
    },
    choosebiao(){

},
    getbiaoqian(){
biaoqian().then(res=>{
this.labellist=res.lableList
})
    },
    shangyibu() {
      this.active = 1
    },
    choseconfim() {


      if(this.activee){
        this.active = 2
      this.options.img=this.activee
      }else{
        this.$message.warning("请选择图片");
      }
      // this.active = 2
      // this.options.img=this.activee
      // console.log(this.options,"选择后")

    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    handleRemovee(file) {
    },
    handlePrevieww(file) {
      console.log(file);
      if(file.code==500){
        this.$message.warning(file.msg);
       }else{
        this.getListt()
       }
    },
    handleExceedd(files) {

    },
    beforeRemovee(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleClosee(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    handleClose(done) {
      this.dialogVisible = false
    },
    getListt(){
      this.active=1
      this.activee=""
      this.loading = true;
      listImg(this.queryParamss).then(response => {
        this.imgList = response.rows;
        this.totall = response.total;
        this.loading = false;
      });
    },
    choseimg() {
      this.visible=true
      this.active=1
      this.activee=""
      this.options.img=""
      console.log(this.options,"选择")
      this.loading = true;
      listImg(this.queryParamss).then(response => {
        this.imgList = response.rows;
        this.totall = response.total;
        this.loading = false;
      });
    
      this.dialogVisible = true
    },
    handleRemove(file) {
      console.log(file)
      let urll=file.response.url
      delvideo({url:urll} ).then(res=>{
        console.log(res)
      })
      this.form.videoUrl=null
    },
    handlePreview(file) {
      let str = file.url
      this.form.videoUrl=str
      // if (this.subfile.length != 0) {
      //   // this.subfile.forEach(el => {
      //     let item = this.subfile.find(ele => ele.authenticationDataId == str.authenticationDataId);
      // 			if (!item) {
      // 				this.subfile.push(str)
      //       }else{
      //         this.subfile.forEach(el => {
      //           if(el.authenticationDataId==str.authenticationDataId){
      //             el.data=str.data
      //           }
      //         })
      //       }

      // 	}else{
      //     this.subfile.push(str)
      //   }
    },
    handleExceed(files) {
      this.$message.warning(`只能上传一个文件`);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialTitle: null,
        materialDigest: null,
        materialAuthor: null,
        labelId: null,
        coverUrl: null,
        videoUrl: null,
        reportWechat: null,
        wechatUrl: null,
        wechatMediaId: null,
        userId: null,
        isDelete: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.file=[]
      this.reset();
      this.open = true;
      this.title = "添加视频信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        this.form = response.sourceMaterial;
        this.open = true;
        this.title = "修改视频信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if(this.type){
              if(this.type=="1"){
                addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.type=""
              this.$router.go(-1)
              // this.getList();
            });
              }
            }else{
              addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
            }
          
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>

.imglist {
  width: 100%;

  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;

  .imgitem {
    width: 135px;
    // height: 135px;
    border: 1px solid #f7f7f7;
    border-radius: 5px;
    padding: 10px;
    margin: 10px;
    text-align: center;
    img{
      width: 100%;
    }
    p{
      overflow: hidden;
      text-overflow: ellipsis; //文本超出块元素时以省略号的形式显示

white-space: nowrap; //规定段落中的文本不进行换行
    }
  }
  .activee{
    border: 1px solid #1890ff;
  }
}
.imga{
  width: 400px;
  margin-top: 20px;
  padding: 5px;
  border-radius: 5px;
  img{
    width: 100%;
  border-radius: 5px;

  }
}
</style>
